const express = require('express')
const router = express()
const cheerio = require('cheerio')
const iconv = require("iconv-lite");
const util =require('../../util/acfunutil') ;
const weblist = [
    'https://m.qxs.la/',
    'https://m.x23us.com'
]
router.get('/parse',(req, res) => {
    if(req.query.url){
        util.service.get(req.query.url,{responseType:'arraybuffer'}).then(resp=>{
            const data = resp.data;
            const buf = new Buffer(data,'binary')
            const $  = cheerio.load(iconv.decode(buf,req.query.encoding||'utf-8'),{decodeEntities: false})
            res.send({
                code:200,
                html:$.html()
            })
        }).catch(err=>{
            res.send({code:500,message:'fetch error'})
        })
    }else {
        res.send({code:400,message:'url required'})
    }
})
router.get('/',(req, res) => {
    const page = req.query.page||1;
    const webindex = req.query.web || 0
    let url = weblist[webindex]+`s_${encodeURI(req.query.q)}/${parseInt(page)}/`;
    let add = `?web=${webindex}`;
    if(webindex==0){
        add = '';
    }
    const base = 'https://'+req.header('host')+'/novels';
    const next = base+`?q=${encodeURI(req.query.q)}&page=${parseInt(page)+1}`;
    let prev =base+`?q=${encodeURI(req.query.q)}&page=${parseInt(page)-1}`;
    if(page===1){
        prev = ''
    }
    util.service.get(url,{responseType:'arraybuffer'}).then(resp=>{
        const data = resp.data;
        const buf = new Buffer(data,'binary')
        const $ = cheerio.load(iconv.decode(buf,'gbk'))
        const obj = {results:[],next,prev}
        $('.list ul li a').each((i,e)=>{
            let infos = $(e).text().split('/');
            obj.results.push({
                url:`${base}`+e.attribs.href+add,
                title:infos[0],
                author:infos[1]
            })
        })
        res.send(obj)
    })
})
router.get('/:novelId', (req, res) => {
    const page = req.query.page||1;
    const webindex = req.query.web||0;
    const web = weblist[webindex]
    const base = 'https://'+req.header('host')+'/novels';
    let add = `?web=${webindex}`;
    if(webindex==0){
        add = '';
    }
    let urls = web + req.params.novelId + `-${page}`;
    util.service.get(urls,{responseType:'arraybuffer'}).then(resp=>{
        const data = resp.data;
        const buf = new Buffer(data,'binary')
        const $ = cheerio.load(iconv.decode(buf,'gbk'));
        let totalPage = 1
        if($('.btn_c').last().attr('href')){
            totalPage =parseInt($('.btn_c').last().attr('href').replace('/','').split('-')[1])
        }
        const obj = {title:$('.n-title').text(),chapters:[],total:0,page,totalPage};
        const readbase = req.header('origin')||'https://styang.gitee.io';
        $('.n-chapter').last().find('.chapter a').each((i,e)=>{
            obj.chapters.push({name:e.attribs.title,url:`${base}`+e.attribs.href+add,
                read:`${readbase}/#/novels${e.attribs.href}`})
            obj.total++
        })
        res.send(obj)
    })



})

router.get('/:novelId/:chapterId', (req, res) => {
    const base = 'https://'+req.header('host')+'/novels';
    const webindex = req.query.web||0;
    const web = weblist[webindex]+`${req.params.novelId}/${req.params.chapterId}`
    let add = `?web=${webindex}`;
    if(webindex==0){
        add = '';
    }
    util.service.get(web,{responseType:'arraybuffer'}).then(resp=>{
        const data = resp.data;
        const buf = new Buffer(data,'binary');
        const  text = iconv.decode(buf,'gbk');
        const $ = cheerio.load(text,{decodeEntities: false})
        const prev = `${base}`+$('.n-prenext a').first().attr('href')+add
        let next = `${base}`+$('.n-prenext a').last().attr('href')+add
        let end = next.indexOf('end')>=0;
        if(end){
            next=''
        }
        const obj = {title:$('.n-title').text(),content:$('#content').html(),prev,next}
        res.send(obj)
    })
})
module.exports = router